package com.chiaching.framwork.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

public class CookieUtil {

    public static String getValueInCookies(HttpServletRequest request, String key) {
        if (request.getCookies() != null) {
            return Arrays.stream(request.getCookies()).filter(cookie -> cookie.getName().equals(key)).map(Cookie::getValue)
                    .findFirst().orElse("");
        }
        return "";
    }

    public static void addCookieToTopDomain(HttpServletRequest request, HttpServletResponse response, String key, String value, int maxAge, boolean isHttpOnly) {
        Cookie cookie = new Cookie(key, value);
        cookie.setDomain(getTopDomain(request));
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        cookie.setHttpOnly(isHttpOnly);
        response.addCookie(cookie);
    }

    public static String getTopDomain(HttpServletRequest request) {
        String serverName = request.getServerName();
        return serverName.substring(serverName.indexOf(".") + 1);
    }

}
